<!--  -->
<template>
    <div>
        <a-tabs  v-model="parentId" @change="tabChange">
            <a-tab-pane :tab="item.cateName" v-for="item in tabList" :key="item.id">
            </a-tab-pane>
            <a-button slot="tabBarExtraContent" style="margin-right: 20px" @click="updateMainClassify">修改主分类</a-button>
            <a-button slot="tabBarExtraContent" @click="delMainClassify">删除主分类</a-button>
        </a-tabs>
        <div class="table-page-search-wrapper">
            <a-form layout="inline">
                <a-row :gutter="48">
                    <a-col :md="8" :sm="24">
                        <a-form-item label="商品名称">
                            <a-input v-model="goodsName" allow-clear placeholder="请输入商品名称" />
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                    </a-col>
                    <a-col :md="8" :sm="24">
                        <a-form-item >
                            <a-button style="margin-right: 20px" type="primary" @click="goDetail()">查询</a-button>
                            <a-button icon="plus" @click="add()">新增</a-button>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>
        <a-table size="small" :columns="columns" :data-source="dataList" :loading="isload" :pagination="{ pageSize: 10, total: total ,showSizeChanger: true,pageSize: size}" @change="handleTableChange">
            <a-avatar  slot="imageUrl" slot-scope="imageUrl" :src="imageUrl" />
            <div slot="status" slot-scope="status">
                <a-switch checked-children="上架" un-checked-children="下架" disabled :checked="status == 1 ? true : false" />
            </div>
            <div slot="goodsInfo" slot-scope="text,record">
                <a-button type="link" @click="goNext(record)">查看</a-button>
            </div>
            <div slot="spFloatRatio" slot-scope="spFloatRatio,record">
                <editable-cell :text="`${(spFloatRatio * 100).toString()}`" @change="onCellChange(record.id, 'rank', $event,record,'spFloatRatio')" />
            </div>
            <div slot="opFloatRatio" slot-scope="opFloatRatio,record">
                <editable-cell :text="`${(opFloatRatio * 100).toString()}`" @change="onCellChange(record.id, 'rank', $event,record,'opFloatRatio')" />
            </div>
            <template slot="operation" slot-scope="text, record">
                <div class="editable-row-operations">
                    <a-button type="link" @click="update(record)">修改</a-button>
                    <a-popconfirm
                        title="是否确认删除当前数据?"
                        ok-text="Yes"
                        cancel-text="No"
                        @confirm="del(record)"
                    >
                        <a-button class="errorColor" type="link">删除</a-button>
                    </a-popconfirm>
                </div>
            </template>
        </a-table>
        <!-- 添加、修改、删除商品分类信息 -->
        <a-modal
            title="添加、修改分类"
            :visible="visible"
            :confirm-loading="confirmLoading"
            @ok="handleOk"
            @cancel="visible = false"
            >
            <div>
                <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 17 }">
                    <a-form-item label="分类名称">
                        <a-input v-model="item.cateName" placeholder="请输入分类名称" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="售价浮动比例">
                        <a-input v-model="item.spFloatRatio" placeholder="请输入售价浮动比例" suffix="%" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="原价浮动比例">
                        <a-input v-model="item.opFloatRatio" placeholder="请输入原价浮动比例" suffix="%" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="图片">
                        <a-tag color="#f50">
                            修改时，如果上传图片就会覆盖掉之前的图片，如果不修改就无需上传
                        </a-tag>
                        <div class="clearfix">
                            <a-upload
                            list-type="picture-card"
                            :file-list="fileList"
                            
                            @change="handleChange"
                            >
                            <div v-if="fileList.length < 1">
                                <a-icon type="plus" />
                                <div class="ant-upload-text">
                                    选择图片
                                </div>
                            </div>
                            </a-upload>
                        </div>
                    </a-form-item>
                    <a-form-item label="排序" help="0最小，99最大">
                        <a-input v-model="item.sort" placeholder="请输入排序数字" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="是否上架">
                        <a-radio-group v-model="item.status" >
                            <a-radio  v-for="(item,i) in statusList" :key="i" :value="item.id">{{item.name}}</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>

        <a-modal
            title="添加、修改分类"
            :visible="mainVisible"
            :confirm-loading="mainConfirmLoading"
            @ok="mainHandleOk"
            @cancel="mainVisible = false"
            >
            <div>
                <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 17 }">
                    <a-form-item label="分类名称">
                        <a-input v-model="item.cateName" placeholder="请输入分类名称" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="图片">
                        <a-tag color="#f50">
                            修改时，如果上传图片就会覆盖掉之前的图片，如果不修改就无需上传
                        </a-tag>
                        <div class="clearfix">
                            <a-upload
                            list-type="picture-card"
                            :file-list="fileList"
                            
                            @change="handleChange"
                            >
                            <div v-if="fileList.length < 1">
                                <a-icon type="plus" />
                                <div class="ant-upload-text">
                                    选择图片
                                </div>
                            </div>
                            </a-upload>
                        </div>
                    </a-form-item>
                    <a-form-item label="排序" help="0最小，99最大">
                        <a-input v-model="item.sort" placeholder="请输入排序数字" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="是否上架">
                        <a-radio-group v-model="item.status" >
                            <a-radio  v-for="(item,i) in statusList" :key="i" :value="item.id">{{item.name}}</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>
    </div>
</template>

<script>
const EditableCell = {
    template: `
        <div class="editable-cell">
            <div v-if="editable" class="editable-cell-input-wrapper">
            <a-input :value="value" @change="handleChange" @pressEnter="check" /><a-icon
                type="check"
                class="editable-cell-icon-check"
                @click="check"
            />
            </div>
            <div v-else class="editable-cell-text-wrapper">
            {{ text || ' ' }}%
            <a-icon type="edit" class="editable-cell-icon" @click="edit" />
            </div>
        </div>
        `,
    props: {
        text: String,
    },
    data() {
        return {
            value: this.text,
            editable: false,
        };
    },
    methods: {
        handleChange(e) {
            const value = e.target.value;
            this.value = value;
        },
        check() {
            this.editable = false;
            this.$emit('change', this.value);
        },
        edit() {
            this.value  = this.text;
            this.editable = true;
        },
    },
};

import { columns } from './classifyTable';
import { queryClassify , updateClassify } from '@/api/mall/classify';
import { queryBrand }  from '@/api/brand';
export default {
    data () {
        return {
            userId: undefined,
            brandId: this.global.brandId,
            brandList: [],
            isload: false,
            dataList: [],
            size: 10,
            page: 1,
            total: 0,
            columns,
            visible: false,
            confirmLoading: false,
            item: {
                id: undefined,
                level : '1',
                parentId : '0',
                status : '0',
                sort: '1',
                cateName : ''
            },
             statusList: [
                { id: '1', name: '是'},
                { id: '0', name: '否'},
            ],
             levelList: [
                { id: '1', name: '一级分类'},
                { id: '2', name: '二级分类'},
            ],
            isAdd: true,
            innerData:[],
            expandedRowKeys:[],
            fileList: [],
            leveClassify:[],//  分类添加
            parentId: '',
            tabList: [],
            goodsName: '',
            mainVisible: false,
            mainConfirmLoading: false,
        };
    },
    components: {
        EditableCell,
    },
    async created(){
        this.getData()
    },
    methods: {
        getData(){
            let _this = this
            _this.isload = true
            const params = {
                'brandId':_this.brandId,
                'sort': 'sort',
                'level': '1',
                'parentId': '0',
                'size': 99,
            }
            _this._queryClassify(params,1)
        },
        _queryClassify(params,type){
            var _this=this
            queryClassify(params)
            .then(res=>{
                _this.isload = false
                if(res.success){
                    // _this.dataList = res.data.content;
                    // _this.total = res.data.totalElements
                    if(type==1){
                        res.data.content.forEach((item,index) => {
                            item.index=index
                            _this.dataList.push(item)
                        });
                        _this.tabList = res.data.content;
                        if(res.data.content.length > 0){
                            _this.parentId = res.data.content[0].id;
                            const params = {
                                'brandId':_this.brandId,
                                'sort': 'sort',
                                'level': '2',
                                'parentId': _this.parentId,
                                'size':_this.size,
                                'page':_this.page - 1,
                            }
                            _this._queryClassify(params,2);
                        }
                    }else{
                        _this.dataList = res.data.content;
                        _this.total = res.data.totalElements
                    }
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            let _this = this;
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            // this.getData()
            const params = {
                'brandId':_this.brandId,
                'sort': 'sort',
                'level': '2',
                'parentId': _this.parentId,
                'size':_this.size,
                'page':_this.page - 1,
            }
            _this._queryClassify(params,2);
        },
        // 查询下级分类
        expand(expanded, record) {
                 let temp = []
                    if (expanded) {
                        temp.push(record.index)
                    }
                  this.expandedRowKeys=temp
                   const params = {
                        'brandId':this.brandId,
                        'parentId':record.id,
                        'size':100,
                        'page':0,
                    }
                   this._queryClassify(params,2)

        },

        // 添加
        add(){
            this.isAdd = true
            this.item={
                id : '',
                status : '0',
                cateName :'',
                spFloatRatio: '',
                opFloatRatio: '',
                sort: '1',
            }
            this.fileList = []
            this.visible = true
            //  this.levelChange()
        },
        // 修改
        update(item){
            this.isAdd = false
            this.item = JSON.parse(JSON.stringify(item))
            this.item.spFloatRatio = item.spFloatRatio * 100;
            this.item.opFloatRatio = item.opFloatRatio * 100;
            this.fileList = []
            this.visible = true
        },
        // 选择图片
        handleChange({ fileList }) {
            this.fileList = fileList;
        },
        // 确认添加、修改
        handleOk(){
             let _this = this
            if(_this.item.cateName == ''){
                _this.$message.warning('请输入分类名称！');
                return
            }
           
            var formData = new FormData()
            formData.append('brandId',_this.brandId)
            formData.append('id',_this.item.id)
            formData.append('status',_this.item.status)
            formData.append('cateName',_this.item.cateName)
            formData.append('sort',_this.item.sort)
            formData.append('parentId',_this.parentId)
            formData.append('level','2')
            formData.append('spFloatRatio',_this.item.spFloatRatio / 100)
            formData.append('opFloatRatio',_this.item.opFloatRatio / 100)
            _this.fileList.forEach(item=>{
                formData.append('file',item.originFileObj)
            })
            // formData.append('isFile',true)
            updateClassify(formData)
            .then(res=>{
                if(res.success){
                    _this.$notification['success']({
                        message: '提示',
                        description: _this.isAdd ? '添加成功' : '修改成功',
                        duration: 8,
                    })
                    // _this.getData()
                    const params = {
                        'brandId':_this.brandId,
                        'sort': 'sort',
                        'level': '2',
                        'parentId': _this.parentId,
                        'size':_this.size,
                        'page':_this.page - 1,
                    }
                    _this._queryClassify(params,2);
                    _this.visible = false
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 删除消息
        del(item){
            let _this = this
              var formData = new FormData()
                formData.append('brandId',item.brandId)
                formData.append('id',item.id)
                formData.append('isDelete',1)
           
            updateClassify(formData)
            .then(res=>{
                if(res.success){
                    _this.$notification['success']({
                        message: '提示',
                        description: '删除成功',
                        duration: 8,
                    })
                    const params = {
                        'brandId':_this.brandId,
                        'sort': 'sort',
                        'level': '2',
                        'parentId': _this.parentId,
                        'size':_this.size,
                        'page':_this.page - 1,
                    }
                    _this._queryClassify(params,2);
                    // _this.getData()
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 添加主分类
        addMainClassify(){
            let _this = this;
            var formData = new FormData()
            formData.append('brandId',_this.brandId)
            formData.append('status','1')
            formData.append('cateName','鲜花')
            formData.append('level','1')
            formData.append('parentId','0')
            updateClassify(formData)
            .then(res=>{
                if(res.success){
                    _this.getData()
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 查看商品详情
        goNext(item){
            localStorage.setItem('classifyItem',JSON.stringify(item))
            this.$router.push({ path: '/newMall/goods',})
        },
        onCellChange(key, dataIndex, value,item,type) {
            const dataSource = [...this.dataList];
            const target = dataSource.find(item => item.id === key);
            let _this = this;
            console.log(key,dataIndex,value,'oncellchange',item)
            var formData = new FormData()
            formData.append('brandId',_this.brandId)
            formData.append('id',key)
            formData.append('status',item.status)
            formData.append('cateName',item.cateName)
            formData.append('sort',item.sort)
            if(type == 'spFloatRatio'){
                formData.append('opFloatRatio',item.opFloatRatio)
                formData.append('spFloatRatio',value / 100)
            }else{
                formData.append('opFloatRatio',value / 100)
                formData.append('spFloatRatio',item.spFloatRatio)
            }
            updateClassify(formData)
            .then(res => {
                if(res.success){
                    _this.getData();
                    _this.$notification['success']({
                        message: '提示',
                        description: "修改成功",
                        duration: 8,
                    })
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 一级分类切换
        tabChange(item){
            console.log(item)
            let _this = this;
            _this.parentId = item;
            _this.page = 1;
            const params = {
                'brandId':_this.brandId,
                'sort': 'sort',
                'level': '2',
                'parentId': _this.parentId,
                'size':_this.size,
                'page':_this.page - 1,
            }
            _this._queryClassify(params,2);
        },
        // 查询功能
        goDetail(){
            localStorage.setItem('classifyItem',JSON.stringify({'id': '','cateName': ''}))
            this.$router.push({ path: '/newMall/goods',query: {'goodsName': this.goodsName}})
        },
        // 主分类修改
        updateMainClassify(){
            let _this = this;
            const classify = _this.tabList.find(item => item.id == _this.parentId);
            _this.updateMain(classify);
        },
        updateMain(item){
            this.item = JSON.parse(JSON.stringify(item));
            this.fileList = []
            this.mainVisible = true
        },
        mainHandleOk(){
            let _this = this;
            var formData = new FormData()
            formData.append('brandId',_this.brandId)
            formData.append('id',_this.item.id)
            formData.append('status',_this.item.status)
            formData.append('cateName',_this.item.cateName)
            formData.append('sort',_this.item.sort)
            formData.append('parentId',_this.item.parentId)
            formData.append('level',_this.item.level)
            _this.fileList.forEach(item=>{
                formData.append('file',item.originFileObj)
            })
            updateClassify(formData)
            .then(res=>{
                if(res.success){
                    _this.$notification['success']({
                        message: '提示',
                        description: '修改成功',
                        duration: 8,
                    })
                    // _this.getData()
                    const params = {
                        'brandId':_this.brandId,
                        'sort': 'sort',
                        'level': '1',
                        'parentId': '0',
                        'size':99,
                        'page':0,
                    }
                    _this._queryClassify(params,1);
                    _this.mainVisible = false
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 主分类删除
        delMainClassify(){
            let _this = this;
            const classify = _this.tabList.find(item => item.id == _this.parentId);
            _this.$confirm({
                title: '温馨提示',
                content: `是否删除当前 ${classify.cateName} ?`,
                onOk(){
                    _this.del(classify);
                },
            })
        },
    }
}

</script>
<style>
.editable-cell {
  position: relative;
}

.editable-cell-input-wrapper,
.editable-cell-text-wrapper {
  padding-right: 24px;
}

.editable-cell-text-wrapper {
  padding: 5px 24px 5px 5px;
}

.editable-cell-icon,
.editable-cell-icon-check {
  position: absolute;
  right: 0;
  width: 20px;
  cursor: pointer;
}

.editable-cell-icon {
  line-height: 18px;
  display: none;
}

.editable-cell-icon-check {
  line-height: 28px;
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}

.editable-cell-icon:hover,
.editable-cell-icon-check:hover {
  color: #108ee9;
}

.editable-add-btn {
  margin-bottom: 8px;
}
</style>